import React, {useCallback, useEffect, useState} from 'react';
import {Breadcrumb, Button, Form, Input, message, Modal, Select, Space, Table, TableProps} from 'antd';
import {useNavigate} from "react-router-dom";
import type {RepairRequest} from "@/types/resp/repairRequest";
import repairRequestApi from '@/api/repairRequestApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import RepairRequestAdd from "@/pages/repairRequest/RepairRequestAdd.tsx";
import RepairRequestView from "@/pages/repairRequest/RepairRequestView.tsx";
import BuildingSelector from "@/pages/building/BuildingSelector.tsx";
import RoomSelector from "@/pages/room/RoomSelector.tsx";
import StaffSelector from "@/pages/staff/StaffSelector.tsx";
import { exportToExcel } from '@/utils/exportUtil.ts'
import {getPropertyRepairRequestStatusText} from "@/utils/dictTranslator.ts";


const RepairRequestList: React.FC = () => {

  const navigate = useNavigate();
  const [messageApi, messageContextHolder] = message.useMessage();
  const [modal, modalContextHolder] = Modal.useModal();

  const handleClick = (path: string) => {
    navigate(path);
  };

  const breadcrumbsItems = [
    {title: '首页', className: 'breadcrumbHome', onClick: () => handleClick('/Home')},
    {title: '报修信息列表'}
  ]

  const [form] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    form.resetFields();
  };

  const [data, setData] = useState<RepairRequest[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<RepairRequest>> = await repairRequestApi.find(form.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<RepairRequest> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<RepairRequest>['columns'] = [
    {title: '楼栋名称', dataIndex: 'buildingName', key: 'buildingName'},
    {title: '单元房号', dataIndex: 'roomNumber', key: 'roomNumber'},
    {title: '问题描述', dataIndex: 'description', key: 'description', ellipsis: true},
    {title: '报修时间', key: 'requestTime', render: (_, record) => (
      <div>{record.requestTime ? record.requestTime.format('YYYY-MM-DD HH:mm:ss') : ''}</div>
    )},
    {title: '状态', key: 'status', render: (_, record) => (
        <span>
        {(function () {
          if (record.status === 10) return '待处理';
          else if (record.status === 20) return '处理中';
          else if (record.status === 30) return '已完成';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '维修保养人员', dataIndex: 'staffName', key: 'staffName'},
    {title: '备注', dataIndex: 'remark', key: 'remark'},
    {title: '完成时间', key: 'finishTime', render: (_, record) => (
      <div>{record.finishTime ? record.finishTime.format('YYYY-MM-DD HH:mm:ss') : ''}</div>
    )},
    {
      title: '操作',
      key: 'action',
      width: '250px',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" onClick={() => editRow(record.id)}>编辑</Button>
          <Button danger onClick={() => delRow(record.id)}>删除</Button>
          <Button color="primary" variant="outlined" onClick={() => detailRow(record)}>详情</Button>
        </Space>
      ),
    },
  ];

  const [repairRequestAddVisible, setRepairRequestAddVisible] = useState(false);
  const [repairRequestViewVisible, setRepairRequestViewVisible] = useState(false);
  const [selectedRepairRequestId, setSelectedRepairRequestId] = useState(0)
  const [selectedRepairRequest, setSelectedRepairRequest] = useState({})

  const onAdd = () => {
    setSelectedRepairRequestId(0)
    setRepairRequestAddVisible(true)
  };

  const editRow = (id: number) => {
    setSelectedRepairRequestId(id)
    setRepairRequestAddVisible(true)
  };

  const delRow = useCallback(async (id: number) => {
    const confirmed = await modal.confirm({
      title: '删除提示',
      content: (
        <>
          确定要删除吗?
        </>
      ),
      okText: '确定',
      cancelText: '取消',
      type: 'warning'
    });

    if (confirmed) {
      repairRequestApi.del(id)
        .then((resp) => {
          if (resp && resp.code === 1) {
            messageApi.success('删除成功!')
            onSearch()
          } else {
            messageApi.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
          }
        })
        .catch(error => {
          console.error('操作失败:', error)
        })
    }
  }, [modal]);

  const detailRow = (record: RepairRequest) => {
    setSelectedRepairRequest(record)
    setRepairRequestViewVisible(true)
  };

  const [buildingSelectorVisible, setBuildingSelectorVisible] = useState(false);
  const findBuilding = () => {
    setBuildingSelectorVisible(true);
  }
  const handleBuildingSelected = (selectedBuilding: { buildingId?: number; buildingName?: string; }) => {
    setBuildingSelectorVisible(false)
    if (selectedBuilding && 'buildingId' in selectedBuilding) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      buildingId: selectedBuilding['buildingId'],
      buildingName: selectedBuilding['buildingName'],
      }));
    }
  };
  const handleCloseBuildingSelector = () => {
    setBuildingSelectorVisible(false)
  };
  const [roomSelectorVisible, setRoomSelectorVisible] = useState(false);
  const findRoom = () => {
    setRoomSelectorVisible(true);
  }
  const handleRoomSelected = (selectedRoom: { roomId?: number; roomNumber?: string; }) => {
    setRoomSelectorVisible(false)
    if (selectedRoom && 'roomId' in selectedRoom) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      roomId: selectedRoom['roomId'],
      roomNumber: selectedRoom['roomNumber'],
      }));
    }
  };
  const handleCloseRoomSelector = () => {
    setRoomSelectorVisible(false)
  };
  const [staffSelectorVisible, setStaffSelectorVisible] = useState(false);
  const findStaff = () => {
    setStaffSelectorVisible(true);
  }
  const handleStaffSelected = (selectedStaff: { staffId?: number; staffName?: string; }) => {
    setStaffSelectorVisible(false)
    if (selectedStaff && 'staffId' in selectedStaff) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      staffId: selectedStaff['staffId'],
      staffName: selectedStaff['staffName'],
      }));
    }
  };
  const handleCloseStaffSelector = () => {
    setStaffSelectorVisible(false)
  };

  const handleCloseRepairRequestAdd = () => {
    setRepairRequestAddVisible(false)
  };

  const handleCloseRepairRequestView = () => {
    setRepairRequestViewVisible(false)
  };

  const onExport = () => {
    const headers = ['楼栋名称','单元房号','问题描述','报修时间','状态','维修保养人员','备注','完成时间']
    repairRequestApi.find(form.getFieldsValue()).then(data => {
      if (!data || !data.data || data.data.list.length < 1) {
        messageApi.error('无数据导出')
        return
      }
      const exportData = []
      for (const d of data.data.list) {
        exportData.push([d.buildingName,d.roomNumber,d.description,d.requestTime,getPropertyRepairRequestStatusText(d.status),d.staffName,d.remark,d.finishTime])
      }
      exportToExcel(headers, exportData)
    })
  }

  useEffect(() => {
    onSearch();

    return () => {
    };
  }, []);

  return (
    <div className="repairRequestList">
      {messageContextHolder}
      {modalContextHolder}
      <Breadcrumb items={breadcrumbsItems} style={{marginBottom: 'var(--container-margin)'}} />
      <Form form={form} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="buildingName" label="楼栋名称">
          <Input.Search placeholder="请选择楼栋名称" onSearch={findBuilding} readOnly={true} />
        </Form.Item>
        <Form.Item name="roomNumber" label="单元房号">
          <Input.Search placeholder="请选择单元房号" onSearch={findRoom} readOnly={true} />
        </Form.Item>
        <Form.Item name="status" label="状态">
          <Select placeholder="请选择状态" options={[
            { value: 10, label: <span>待处理</span> },
            { value: 20, label: <span>处理中</span> },
            { value: 30, label: <span>已完成</span> }
          ]} style={{width: 'var(--select-width)'}} />
        </Form.Item>
        <Form.Item name="staffName" label="维修保养人员">
          <Input.Search placeholder="请选择维修保养人员" onSearch={findStaff} readOnly={true} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onAdd}>新增</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" onClick={onExport}>导出</Button>
        </Form.Item>
      </Form>
      <Table<RepairRequest> columns={columns} dataSource={data} size="small" rowKey={record => record.id} pagination={{ position: ["bottomCenter"] }} style={{marginTop: 'var(--container-margin)'}} />
      <BuildingSelector visible={buildingSelectorVisible} onBuildingSelected={handleBuildingSelected} onCloseBuildingSelector={handleCloseBuildingSelector} />
      <RoomSelector visible={roomSelectorVisible} onRoomSelected={handleRoomSelected} onCloseRoomSelector={handleCloseRoomSelector} />
      <StaffSelector visible={staffSelectorVisible} onStaffSelected={handleStaffSelected} onCloseStaffSelector={handleCloseStaffSelector} />
      <RepairRequestAdd visible={repairRequestAddVisible} onCloseRepairRequestAdd={handleCloseRepairRequestAdd} id={selectedRepairRequestId} />
      <RepairRequestView visible={repairRequestViewVisible} onCloseRepairRequestView={handleCloseRepairRequestView} viewRow={selectedRepairRequest} />
    </div>
  );
};

export default RepairRequestList;
